<template>
  <div class="countdown" v-show="show">
    <span class="curTime">{{curTime}}</span>
    <span>{{countdown}}秒后刷新</span>
  </div>
</template>

<script>
import common from "@/plugins/common.js";
export default {
  name: "countdown",
  props: {
    show: {
      type: Boolean,
      default: false
    },
    number: {
      //单位 秒
      type: Number,
      default: 10
    },
    timeOutCallback: {
      type: Function,
    }
  },
  data() {
    return {
      curTime: common.curentTime(),
      countdown: 0,
      timer: null
    };
  },
  methods: {
    initTimer() {
      if (!this.show) {
        return false;
      }
      this.countdown = this.number;
      this.timer = setInterval(() => {
        if (this.countdown <= 0) {
          this.timeOutCallback();
          this.curTime = common.curentTime();
          clearInterval(this.timer);
          this.initTimer();
        }
        this.countdown--;
      }, 1000);
    },
    destroyTimer() {
      this.countdown = 0;
      clearInterval(this.timer);
    }
  },
  created() {
    this.initTimer();
  },
  beforeDestroy() {
    this.destroyTimer();
  },
  watch: {
    show(newVal) {
      if (!newVal) {
        this.destroyTimer();
      } else {
        this.initTimer();
      }
    }
  }
};
</script>
<style scoped>
.countdown {
}
.curTime {
  margin-right: 8px;
}
</style>